﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Xml.Linq;
using System.Collections.Generic;
using System.IO;
using System.Globalization;
using System.Text;
using System.Reflection;

using Data;
//using EuphoricNation.Page;
using System.Web.Caching;
using System.Collections;

namespace EuphoricNation.Util
{
    /// <summary>
    /// Utility methods for Steppes
    /// </summary>
    public static class Useful
    {
        public static string GetErrorString(string input)
        {
            return string.Format("<p class=\"error\">{0}</p>", input);
        }
        public static string GetErrorSoftString(string input)
        {
            return string.Format("<p class=\"softerror\">{0}</p>", input);
        }
        public static string GetWarningString(string input)
        {
            return string.Format("<p class=\"softerror\">Warning: {0}</p>", input);
        }
        public static string GetMsgString(string input)
        {
            return string.Format("<p><strong>{0}</strong></p>", input);
        }

        /// <summary>
        /// Properly capitalise a string
        /// </summary>
        /// <param name="input">String to capitalise</param>
        /// <returns>Capitalised string</returns>
        public static string Capitalise(string input)
        {
            input = input.ToLower();
            input = input[0].ToString().ToUpper() + input.Substring(1);

            return input;
        }

        /// <summary>
        /// Capitalise all the new words in the sentence
        /// </summary>
        /// <param name="input">String to capitalise</param>
        /// <param name="ignoreCaps">Whether all-capital words should be ignored</param>
        /// <returns>Capitalised string</returns>
        public static string CapitaliseWord(string input, bool ignoreCaps)
        {
            if (ignoreCaps)
                return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(input.ToLower());
            else
                return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(input);
        }

        /// <summary>
        /// Capitalise all words in sentence, ignoring all-caps words
        /// </summary>
        /// <param name="input">String to capitalise</param>
        /// <returns>Capitalised string</returns>
        public static string CapitaliseWord(string input)
        {
            return CapitaliseWord(input, true);
        }

        /// <summary>
        /// Output a permanent redirect to the new address
        /// </summary>
        /// <param name="newAdd">New Address</param>
        public static void RedirectPermanent(string newAdd)
        {
            HttpContext.Current.Response.Status = "301 Moved Permanently";
            HttpContext.Current.Response.AddHeader("Location", newAdd);
            HttpContext.Current.Response.End();
        }

        /// <summary>
        /// Output a temporary redirect to the new address
        /// </summary>
        /// <param name="newAdd">New Address</param>
        public static void RedirectTemporary(string newAdd)
        {
            HttpContext.Current.Response.Status = "302 Moved Temporarily";
            HttpContext.Current.Response.AddHeader("Location", newAdd);
            HttpContext.Current.Response.End();
        }

        /// <summary>
        /// Query String Cleaner - Get Search Query String
        /// </summary>
        /// <param name="strURL">Referring URL</param>
        /// <returns>Entered keywords</returns>
        /// <remarks>From: http://blog.netnerds.net/2007/02/mssql-parse-search-engine-querystrings-for-search-terms/</remarks>
        public static void QSCleaner(string strURL, out string referrer, out string searchEngine, out string keywords)
        {
            int ampStart, slashStart, delimiterStart;
            string strQueryString = "";
            string strDelimiter = "";
            StringBuilder strQueryString2;

            referrer = string.Empty;
            searchEngine = string.Empty;
            keywords = string.Empty;

            strURL = strURL.Replace("aq=", "aa=");
            strURL = strURL.Replace("as_q=", "aa=");
            strURL = strURL.Replace("as_oq=", "aa=");
            strURL = strURL.Replace("as_eq=", "aa=");

            // most used search delimiters
            if (strURL.IndexOf("q=") > 0)
                strDelimiter = "q=";
            else if (strURL.IndexOf("p=") > 0)
                strDelimiter = "p=";
            else if (strURL.IndexOf("query=") > 0)
                strDelimiter = "=";
            else if (strURL.IndexOf("search=") > 0)
                strDelimiter = "search=";
            else if (strURL.IndexOf("qry=") > 0)
                strDelimiter = "qry=";
            else if (strURL.IndexOf("p=") > 0)
                strDelimiter = "p=";
            else if (strURL.IndexOf("words=") > 0)
                strDelimiter = "words=";
            else if (strURL.IndexOf("word=") > 0)
                strDelimiter = "word=";
            else if (strURL.IndexOf("MT=") > 0)
                strDelimiter = "MT=";
            else if (strURL.IndexOf("s=") > 0)
                strDelimiter = "s=";
            else if (strURL.IndexOf("key=") > 0)
                strDelimiter = "key=";
            else
                strDelimiter = "unknown";

            if (strURL.IndexOf(strDelimiter) > 0)
            {
                try
                {
                    delimiterStart = strURL.IndexOf(strDelimiter) + strDelimiter.Length;
                    strQueryString = strURL.Substring(delimiterStart, (strURL.Length - delimiterStart));
                    ampStart = strQueryString.IndexOf("&");
                    if (ampStart > 0)
                        strQueryString = strQueryString.Substring(0, ampStart);

                    slashStart = strQueryString.IndexOf("/");
                    if (slashStart > 0)
                        strQueryString = strQueryString.Substring(0, slashStart - 1);

                    // because I can't get System.Web.HttpUtility.UrlDecode to work
                    strQueryString2 = new StringBuilder(strQueryString);

                    strQueryString2.Replace("%20", " ");
                    strQueryString2.Replace("%21", "!");
                    strQueryString2.Replace("%22", "\"");
                    strQueryString2.Replace("%23", "#");
                    strQueryString2.Replace("%24", "$");
                    strQueryString2.Replace("%25", "%");
                    strQueryString2.Replace("%26", "&");
                    strQueryString2.Replace("%27", "''");
                    strQueryString2.Replace("%28", "(");
                    strQueryString2.Replace("%29", ")");
                    strQueryString2.Replace("%2A", "*");
                    strQueryString2.Replace("%2B", "+");
                    strQueryString2.Replace("%2C", ",");
                    strQueryString2.Replace("%2D", "-");
                    strQueryString2.Replace("%2E", ".");
                    strQueryString2.Replace("%2F", "/");
                    strQueryString2.Replace("%3A", ":");
                    strQueryString2.Replace("%3B", ";");
                    strQueryString2.Replace("%3C", "<");
                    strQueryString2.Replace("%3D", "=");
                    strQueryString2.Replace("%3E", ">");
                    strQueryString2.Replace("%3F", "?");
                    strQueryString2.Replace("%40", "@");
                    strQueryString2.Replace("%5B", "[");
                    strQueryString2.Replace("%5C", "");
                    strQueryString2.Replace("%5D", "]");
                    strQueryString2.Replace("%5E", "^");
                    strQueryString2.Replace("%5F", "_");
                    strQueryString2.Replace("%60", "`");
                    strQueryString2.Replace("%7B", "{");
                    strQueryString2.Replace("%7C", "|");
                    strQueryString2.Replace("%7D", "}");
                    strQueryString2.Replace("+", " ");

                    strQueryString = strQueryString2.ToString();
                }
                catch (Exception)
                {
                    strQueryString = strURL;
                }
            }
            else
                strQueryString = strURL;

            if (strQueryString == strURL)
                referrer = strURL;
            else
            {
                Uri thisUri = new Uri(strURL);
                keywords = strQueryString;
                searchEngine = thisUri.Host;
            }
        }

        /// <summary>
        /// Get the type of content based on content type name
        /// </summary>
        /// <param name="contentName">Content Type Name</param>
        /// <returns>Type, NULL if not found</returns>
        public static Type GetContentType(string contentName)
        {
            Type baseType = typeof(ContentBase);

            return Assembly.GetAssembly(baseType).GetType("Data." + contentName, false, false);
        }

        /// <summary>
        /// Get the path from the raw URL
        /// </summary>
        /// <param name="rawURL">Raw URL</param>
        /// <returns>Path</returns>
        public static string GetPathFromURL(string rawURL)
        {
            int startPos = rawURL.IndexOf(';');

            if (startPos < 0)
                startPos = 0;

            int lastPos = rawURL.IndexOf('?', startPos);

            if (lastPos <= 0)
                lastPos = rawURL.Length;

            if (rawURL.IndexOf("http://", startPos) > -1)
                startPos = rawURL.IndexOf('/', startPos + 8);

            if (startPos < 0)
                startPos = 0;

            lastPos -= startPos;

            return rawURL.Substring(startPos, lastPos);
        }

        /// <summary>
        /// Delete all the files within a directory
        /// </summary>
        /// <param name="path">Path for directory</param>
        public static void EmptyDirectory(string path)
        {
            string[] paths = Directory.GetFiles(path);

            foreach (string _path in paths)
            {
                File.Delete(_path);
            }
        }

        /// <summary>
        /// Clear the cache - dangerous!
        /// </summary>
        /// <param name="cache">Cache to clear</param>
        public static void ClearCache(Cache cache)
        {
            List<string> keys = new List<string>();
            IDictionaryEnumerator enumerator = cache.GetEnumerator();

            while (enumerator.MoveNext())
                keys.Add(enumerator.Key.ToString());

            foreach (string key in keys)
                cache.Remove(key);
        }
    }
}
